#/usr/bin/env python
# coding: utf-8

from ftplib import FTP
import datetime
import re
import os
import paramiko

hostname = 'xxx'
username = 'root'
password = 'xxx'
port = 22

#ftp 连接信息
def ftpConnect():
    ftp_server = '192.168.0.95'
    user = 'xxx'
    password = 'xxx'
    ftp = FTP()
    ftp.encoding = "utf-8"
    ftp.connect(ftp_server, 21)
    ftp.login(user, password)
    print(ftp.getwelcome())
    return ftp

#从ftp下载war包到本机
def downloadFile():
    today = (datetime.datetime.now().strftime("%Y%m%d"))
    ftp = ftpConnect()
    bufsize = 10240
    ftp.cwd("/xxx")
    file_list = ftp.nlst()
    for name in file_list:
        base_dir = "C:\\Users\\xxx\\Desktop\\"
        save_path = os.path.join(base_dir, today)
        if os.path.isdir(save_path) == True:
            pass
        else:
            os.mkdir(save_path)
        file_path = os.path.join(save_path, name)
        f = open(file_path, 'wb')
        file_name = 'RETR ' + name
        ftp.retrbinary(file_name, f.write, bufsize)
        f.close()
    ftp.close()

#上传本地war包到远程服务器
def uptoServer(local_dir, remote_dir):
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    print('upload file start %s' % datetime.datetime.now())
    for root, dirs, files in os.walk(local_dir):
        for filepath in files:
            local_file = os.path.join(root, filepath)
            a = local_file.replace(local_dir, '').replace("\\", '/').lstrip('/')
            remote_file = os.path.join(remote_dir, a)
            try:
                sftp.put(local_file, remote_file)
            except Exception as e:
                sftp.mkdir(os.path.split(remote_dir)[0])
                sftp.put(local_file, remote_file)
    print('upload file success %s' % datetime.datetime.now())
    t.close()

#执行远程脚本
def  updateServer():
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=hostname, port=port, username=username, password=password)
    changefile = 'sh /opt/app/updateServer.sh'
    stdin, stdout, stderr = ssh.exec_command(changefile)
    stdout.read()
    print('deploy finish')
    ssh.close()


if __name__ == '__main__':
    downloadFile()
    today = (datetime.datetime.now().strftime("%Y%m%d"))
    base_dir = 'C:\\Users\\xxx\\Desktop\\'
    local_dir = os.path.join(base_dir, today)
    remote_dir = '/opt/app/'
    uptoServer(local_dir, remote_dir)
    updateServer()

